import router from '@/router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { validatenull } from '@/utils/validate'
import MobileRouter from '@/router/mobile'
import PageRouter from './router/page'
import { getUserByCookie } from '@/api/common'
import { getStore } from '@/utils/store'
import useUserInfoStore from "@/store/userInfo";
import { client_id } from '@/const/const'
// 前一次路由 防止复制链接没有回退路径(针对移动端)
window.preVueRouter = ''
const RList = [...PageRouter, ...MobileRouter]
const isExpandPcRoute = ['/index', '/login', '/knowledge', '/knowledge/all', '/knowledge/my', '/recyclebin', '/detail', '/share'],
    isExpandMobileRoute = ['/mobile/index', '/mobile/login', '/mobile/knowledge', '/mobile/knowledgeinfo', '/mobile/viewfile', '/mobile/recyclebin', '/mobile/share',
        '/mobile/detail']
const setRouterAuthKey = {
    '/setting/control': 'knowledge-control-auth',
    '/setting/knowRole': 'knowledge-libary-auth',
    '/setting/userRole': 'knowledge-user-auth',
    '/setting/label': 'knowledge-label-auth',
    '/setting/template': 'knowledge-static-auth',
    '/setting/dynamic': 'knowledge-dynamic-auth',
    '/setting/plugin': 'knowledge-plugins-auth',
    '/setting/message': 'knowledge-message-auth',
    '/setting/messagelog': 'knowledge-messagelogs-auth',
    '/setting/api': 'knowledge-apidocument-auth'
}
router.beforeEach((to, from, next) => {
    const userStore = useUserInfoStore()
    function _isMobile() {
        let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
        return flag;
    }
    if (to.query.isMobile) {
        sessionStorage.setItem('isMobile', 1)
    }
    if (getCookie('jvs_session_uid') && !getStore({ name: 'access_token' }) && to.path.indexOf('/login') != -1) {
        getUserByCookie({
            client_id: client_id
        }).then(res => {
            if (res.data && res.data.code == 0) {
                let data = res.data.data
                userStore.batchSetStore(data)
            }
        }).catch(err => {
            userStore.LogOut().then(() => {
                next('/login')
            });
            return
        })
    }
    let isMobile = sessionStorage.getItem('isMobile') || 0
    window.preVueRouter = from.path
    // 缓冲设置
    if (to.meta.keepAlive === true) {
        to.meta.$keepAlive = true
    } else {
        NProgress.start()
        if (to.meta.keepAlive === true && validatenull(to.meta.$keepAlive)) {
            to.meta.$keepAlive = true
        } else {
            to.meta.$keepAlive = false
        }
    }
    function isToSettingAuth(value) {
        if (typeof value === 'object') {
            let isAuth = false
            value.forEach((item) => {
                if (userStore.permissions.indexOf(item) != -1) {
                    isAuth = true
                }
            })
            return isAuth
        } else {
            return userStore.permissions.indexOf(value) != -1
        }
    }
    // 防止暴力进入
    if (to.path.indexOf('/setting/') != -1) {
        if (to.path.indexOf('/setting/') != -1 && (isToSettingAuth(['knowledge-user-auth', 'knowledge-libary-auth', 'knowledge-label-auth', 'knowledge-control-auth', 'knowledge-static-auth', 'knowledge-dynamic-auth', 'knowledge-plugins-auth', 'knowledge-message-auth', 'knowledge-messagelogs-auth', 'knowledge-apidocument-auth']))) {
            if (isToSettingAuth(setRouterAuthKey[to.path])) {
                next()
            } else {
                // 匹配第一个路由逻辑
                let nextPath = '/'
                if (isToSettingAuth('knowledge-control-auth')) {
                    nextPath = '/setting'
                } else if (isToSettingAuth('knowledge-libary-auth')) {
                    nextPath = '/setting/knowRole'
                } else if (isToSettingAuth('knowledge-user-auth')) {
                    nextPath = '/setting/userRole'
                } else if (isToSettingAuth('knowledge-label-auth')) {
                    nextPath = '/setting/label'
                } else if (isToSettingAuth('knowledge-static-auth')) {
                    nextPath = '/setting/template'
                } else if (isToSettingAuth('knowledge-dynamic-auth')) {
                    nextPath = '/setting/dynamic'
                } else if (isToSettingAuth('knowledge-plugins-auth')) {
                    nextPath = '/setting/plugin'
                } else if (isToSettingAuth('knowledge-message-auth')) {
                    nextPath = '/setting/message'
                } else if (isToSettingAuth('knowledge-messagelogs-auth')) {
                    nextPath = '/setting/messagelog'
                } else if (isToSettingAuth('knowledge-apidocument-auth')) {
                    nextPath = '/setting/api'
                }
                if (nextPath == from.path) {
                    next(router.currentRoute)
                    NProgress.done()
                } else {
                    next(nextPath)
                }
            }
        } else if (from.path.indexOf('/setting/') != -1) {
            next('/')
        } else {
            if (window.preVueRouter == from.path) {
                next(router.currentRoute)
                NProgress.done()
            } else {
                next(window.preVueRouter)
            }
        }
        return
    }
    // 未配置的路由跳转404
    const value = to.query.src || to.fullPath
    // 查找当前路由是否存在
    let findRouter = (val, routerList) => {
        let bool = false
        for (let i in routerList) {
            if (val.indexOf(routerList[i].path) != -1 || val.split('?')[0].indexOf(routerList[i].path) != -1) {
                if (routerList[i].children && routerList[i].children.length > 0) {
                    if (!bool) {
                        bool = findRouter(val, routerList[i].children)
                    }
                } else {
                    bool = true
                }
            }
        }
        return bool
    }
    if (!validatenull(value)) {
        let newBool = findRouter(value, RList)
        if (newBool) {
            let newRouteTo = null
            let newQuery = to.query
            if ((isMobile || _isMobile()) && (isExpandPcRoute.indexOf(to.path) != -1 || isExpandPcRoute.indexOf(to.name) != -1 || to.path.indexOf('/knowledge/') != -1 || to.path.indexOf('/share/') != -1 || to.path.indexOf('/detail/') != -1) && to.path.indexOf('/mobile') == -1) {
                delete newQuery.isMobile
                const paramsKey = Object.keys(to.params)
                if (paramsKey.length != 0 && to.params.id) {
                    let toPath = `/mobile/knowledgeinfo`
                    if (newQuery.docId) {
                        toPath = `/mobile/viewfile`
                    }
                    newRouteTo = {
                        path: toPath,
                        query: {
                            id: to.params.id,
                            ...newQuery
                        }
                    }
                } else if (paramsKey.length != 0 && to.params.type) {
                    newRouteTo = {
                        path: `/mobile/knowledge`,
                        query: {
                            id: to.params.id,
                            ...newQuery
                        }
                    }
                } else {
                    newRouteTo = {
                        path: `/mobile${to.path}`,
                        query: newQuery
                    }
                }
            } else if (!isMobile && !_isMobile() && (isExpandMobileRoute.indexOf(to.path) != -1 || isExpandMobileRoute.indexOf(to.name) != -1 || to.path.indexOf('/mobile/share/') != -1 || to.path.indexOf('/mobile/detail/') != -1)) {
                let newReplacePath = to.path.replace('/mobile', '')
                if (newReplacePath == '/knowledge') {
                    newRouteTo = {
                        path: `/knowledge/all`,
                        query: newQuery
                    }
                } else if (newReplacePath == '/knowledgeinfo' && newQuery.id) {
                    newRouteTo = {
                        path: `/knowledge/all/${newQuery.id}`,
                    }
                } else if (newReplacePath == '/viewfile' && newQuery.knId) {
                    newRouteTo = {
                        path: `/knowledge/all/${newQuery.knId}`,
                        query: newQuery
                    }
                } else {
                    newRouteTo = {
                        path: newReplacePath,
                        query: newQuery
                    }
                }
            }
            if (newRouteTo) {
                next(newRouteTo)
            } else {
                next()
            }
        } else {
            next('/404')
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

function getCookie(cname) {
    let name = cname + "=";
    let ca = document.cookie.split(";");
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
}